﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using D3;
using D3.Pathing;
using KCBF.Modules.AI.TreeSharp;
using NYTBD;
using NYTBD.Modules;
using Action = KCBF.Modules.AI.TreeSharp.Action;

namespace KCBF.Modules.AI
{
    class MoveToPosition : Decorator
    {
        public const string PathProperty = "path";
        public const string NextMoveProperty = "next_move";

        private Path _path;
        private Point _cur;
        private Point _target = null;


        private bool _isFinnished = false;


        public MoveToPosition(float x, float y)
            : base(null, null)
        {
            _target = new Point((int)x, (int)y);
            _cur = new Point(int.MaxValue, int.MaxValue);

            Runner = context =>
            {
                if (Squanto.GetDistance(_target.X, _target.Y) < 3) return false;
                return true;
            };

            var myChild = new PrioritySelector();

            myChild.AddChild(new Decorator(rem => _path == null,
                new Action(delegate
                               {
                                   _path = Multiverse.GetCurrentMap().ComputePath(_target.X, _target.Y);

                    var tmp = _path.GetNextNode();
                    var tmpP = _path.MapToD3Coords(tmp.X, tmp.Y);

                    _cur = new Point((int)tmpP[0], (int)tmpP[1]);

                    return RunStatus.Success;

                })));

            myChild.AddChild(new Decorator(ret => Squanto.GetDistance(_cur.X, _cur.Y) > Squanto.MinDistDefault,
               new Sequence(
                   new Action(delegate
                   {

                       Squanto.WalkAtomic(_cur.X, _cur.Y);
                       return RunStatus.Success;
                   }),
                  new WaitContinue(50, rem => false, new ActionAlwaysFail())
               )));

            myChild.AddChild(new Action(delegate
            {

                if (_path.Count() == 0)
                {
                    _path = null;
                    _isFinnished = true;
                    return (RunStatus.Failure);
                }

                var tmp = _path.GetNextNode();
                var tmpP = _path.MapToD3Coords(tmp.X, tmp.Y);

                _cur = new Point((int)tmpP[0], (int)tmpP[1]);

                return (RunStatus.Success);
            }));

            Children[0] = myChild;
        }

        public override string ToString()
        {
            return "Walking To: " + _target;
        }

    }
}
